'use strict';

const Controller = require('egg').Controller;
const { ObjectId } = require("mongodb")
class CollectController extends Controller {
  async index() {
    const { ctx } = this;
    console.log(ctx.request.body);
    var { id, collected } = ctx.request.body
    collected = (collected == "true")?true:false
    // console.log(collect);
    var db = this.app.mongodb;
    //1.更改collect
    await db.collection("article").updateOne({ _id: ObjectId(id) }, { $set: { collected: collected } })
    //2.根据id查询对应的数据
    var res = await ctx.service.article.find(id)
    var item = res[0]
    // item._id = ObjectId(id)
    //3.存数据的时候 1-1 collected == true 1-2 数据库中没有对应的id字段的数据
    try {
      if (collected) {
        await db.collection("user").insertOne(item)
        ctx.body = {
          status: 200,
          msg: "收藏成功"
        }
      }  else {
        await db.collection("user").deleteOne({ _id: ObjectId(id) })
        ctx.body = {
          status: 200,
          msg: "取消收藏"
        }
      }

    } catch (err) {
      this.app.logger.error(err)
      ctx.body = {
        status: 400,
        msg: "数据库中数据已经存在，请不要重复添加"
      }
    }

  }
}

module.exports = CollectController;
